#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/12/6 21:16
# @Author  : 唐松
# @File    : requests_util.py
# @Software: PyCharm

import json
import re
import requests
from util_tools.logger_util import logs


class RequestsUtil:

    def __init__(self):

        pass

    @classmethod
    def _decode_unicode_escape(cls, response_text):
        """
        :param response_text: 包含可能 Unicode 转义字符的响应文本
        :return: 理后的文本，已解码 Unicode 转义字符
        """
        if re.search(r"\\u[0-9a-fA-F]{4}", response_text):
            return response_text.encode().decode('unicode_escape')
        return response_text

    def send_request(self, **kwargs):
        """
        发送请求
        :param kwargs: 请求参数
        :return:
            response: 请求响应
        """
        with requests.Session() as session:
            response = None
            try:
                # 发送请求并获取响应
                response = session.request(**kwargs)
                # 处理响应中的 Unicode 转义字符
                decoded_text = self._decode_unicode_escape(response.text)
                response._content = decoded_text.encode()  # 更新响应内容

                # # 注释掉的 Cookie 处理逻辑，可根据需要启用
                # if response.cookies:
                #     cookies_dict = requests.utils.dict_from_cookiejar(response.cookies)
                #     write_extract_yaml({'Cookie': cookies_dict})

            except requests.exceptions.ConnectionError:
                logs.error('接口请求异常,可能是request的链接过多或者速度过快导致程序报错! ')
            except requests.exceptions.RequestException as e:
                logs.error('请求异常,请检查系统数据是否正常!')
            return response

    def execute_request(self, name, method, url, headers=None, cookies=None, files=None, **kwargs):
        """
        执行请求
        :param name: 接口名称
        :param method: 请求方式
        :param url: 请求地址
        :param headers: 请求头
        :param cookies: cookies
        :param files:   文件上传
        :param kwargs:  请求参数 如data、json、params等
        :return:
        """
        logs.info('---------------------------------接口测试开始---------------------------------')
        logs.info(f'接口名称: {name}')
        logs.info(f'请求地址: {url}')
        logs.info(f'请求方式: {method}')
        logs.info(f'headers值: {headers}')
        logs.info(f'cookies值: {cookies}')
        # 检查是否存在关键字参数
        if kwargs:
            # 检查是否有 data/json/params 中的任意一个
            if any(k in kwargs for k in ("data", "json", "params")):
                # 获取第一个键值对（参数类型和参数值）
                param_type, param_value = next(iter(kwargs.items()))
                try:
                    # 如果是字典或列表，转换为JSON字符串；否则保持原样
                    param_display = json.dumps(param_value, ensure_ascii=False) if isinstance(param_value, (
                    dict, list)) else param_value
                except TypeError:
                    # 处理不可JSON序列化的对象，转换为字符串表示
                    param_display = str(param_value)
                logs.info(f"参数类型: {param_type}")
                logs.info(f"参数值: {param_display}")

        response = self.send_request(
            method=method,
            url=url,
            headers=headers,
            cookies=cookies,
            files=files,
            timeout=10,
            verify=True,
            **kwargs)

        return response


if __name__ == '__main__':
    url = "https://oms-test6.meiyunji.net/oms/sku/list"
    method = 'post'
    headers = {
        "Content-Type": "application/json; charset=utf-8"
    }
    cookies = {
        'cookies': 'MYJ_wig5buyoga=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJhZDJhMDYxNC0xZDczLTRlNzMtYTc1Yy1hZTlmOGU0ZmU3YjMlMjIlMkMlMjJ1c2VySWQlMjIlM0ElMjIxNDMwJTIyJTJDJTIycGFyZW50SWQlMjIlM0ElMjIxMjIlMjIlMkMlMjJzZXNzaW9uSWQlMjIlM0ExNzQ3MTkxNzI5NTY0JTJDJTIyb3B0T3V0JTIyJTNBZmFsc2UlMkMlMjJsYXN0RXZlbnRUaW1lJTIyJTNBMTc0NzE5MjI5MTQwMiUyQyUyMmxhc3RFdmVudElkJTIyJTNBMzIlN0Q=; MYJ_MKTG_wig5buyoga=JTdCJTdE; oms_u=0O7VU868%2BGN9idGLWGUaC%2BJe5C0mVYSKQYaHuW9uWK3vL4CKOiqYyjlx37hvpkePrWwcb%2FjAihWIiShvGuIMswGN%2Blpy4BqDkvrtLWhqsq3Nuk2SedbzV4OpLv68xqpYeHEISBTcq9slyPJVJ7t37YVtzAOenQaDFXUUkMxufQftdJCwKl0QjX%2Fg7LtWNl7%2BZawpnyUPY889r68xwG9gBIJCNEiTYAS3PZyIYkTqIrWPT1EpVNpmSh0%2F8kdKPCr2XkE1qn0sI%2F8x0VcIo14n4IxeGyD2t%2Bh3Uns4J9OzgaQd0HZPQi8wmLxWKDM9WaGGhaW9AGotNy1F4MXIj%2FjGWB4xD1pgG7OHFuIXhzIaXiY%3D; MYJ_MKTG_u2j1jks593=JTdCJTdE; MYJ_u2j1jks593=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJiNDkyOTUyZC1lODk3LTQxZmYtYjEyNy0wNTM5OWU5ZTAxNmYlMjIlMkMlMjJ1c2VySWQlMjIlM0ElMjIxMjIlMjIlMkMlMjJwYXJlbnRJZCUyMiUzQSUyMjEyMiUyMiUyQyUyMnNlc3Npb25JZCUyMiUzQTE3NTI0NzA1ODk0NDglMkMlMjJvcHRPdXQlMjIlM0FmYWxzZSUyQyUyMmxhc3RFdmVudElkJTIyJTNBMTE3JTdE; MYJ_wig5buyoga=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJhZDJhMDYxNC0xZDczLTRlNzMtYTc1Yy1hZTlmOGU0ZmU3YjMlMjIlMkMlMjJ1c2VySWQlMjIlM0ElMjIxNDMwJTIyJTJDJTIycGFyZW50SWQlMjIlM0ElMjIxMjIlMjIlMkMlMjJzZXNzaW9uSWQlMjIlM0ExNzUyNDc0MTgzMDY2JTJDJTIyb3B0T3V0JTIyJTNBZmFsc2UlMkMlMjJsYXN0RXZlbnRJZCUyMiUzQTMyJTdE; JSESSIONID=37F034F761B441E5CBD0971675BDDFFB'
    }
    data = {
        "createBeginTime": '',
        "createEndTime": '',
        "inquireType": 2,
        "searchType": 'sku',
        "searchContent": '',
        "type": '',
        "pageNo": 1,
        "pageSize": 50
    }
    send = RequestsUtil()
    res = send.execute_request(name=None, url=url,headers=headers, cookies=cookies, method=method, json=data)
    print(res.json())
